package com.feedgraph;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;

public class GCMIntentService extends  GCMBaseIntentService {
	
	static final private String TAG = "GCMIntentService";

	@Override
	protected void onError (Context arg0, String arg1) {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void onMessage (Context arg0, Intent intent) {
		try {
			Log.d(TAG, "received message");
			Log.d(TAG, intent.getStringExtra ("JSONString"));
			JSONObject json = new JSONObject(intent.getStringExtra ("JSONString"));
			if (mFeedService != null) mFeedService.handleItemMessage (FeedManager.parseFeedItem (json));
		}
		catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		bindFeedService();
	}
	
	@Override
	public void onDestroy() {
		unbindFeedService();
		super.onDestroy ();
	}

	@Override
	protected void onRegistered (Context arg0, String arg1) {
		Log.d (TAG, "onRegistered");
		
	}

	@Override
	protected void onUnregistered (Context arg0, String arg1) {
		Log.d (TAG, "onUnregistered");
	}
	
	protected static FeedService mFeedService;

	private ServiceConnection mFeedServiceConn = new ServiceConnection () {

		@Override
		public void onServiceConnected (ComponentName arg0, IBinder service) {

			mFeedService = ((FeedService.LocalBinder) service).getService ();

			Log.d (TAG, "bound to FeedService");
		}

		@Override
		public void onServiceDisconnected (ComponentName name) {

			mFeedService = null;

			Log.d (TAG, "disconnected from FeedService");

		}

	};

	private boolean mIsFeedBound;
	
	protected void bindFeedService () {
		Log.d (TAG, "binding to FeedService");

		// Establish a connection with the service. We use an explicit
		// class name because we want a specific service implementation that
		// we know will be running in our own process (and thus won't be
		// supporting component replacement by other applications).

		boolean success = bindService (FeedService.getIntent (this), mFeedServiceConn,
				Context.BIND_AUTO_CREATE);
		
		if (!success) {
			throw new Error("failed to bind to FeedService");
		}
		
		mIsFeedBound = true;
	}
	
	protected void unbindFeedService () {
		if (mIsFeedBound) {
			// Detach our existing connection.
			unbindService (mFeedServiceConn);
			mIsFeedBound = false;
		}
	}

}
